const user = require("./user");
const tokeninfo = user.getTokenInfo();
const axios = require("axios");
const querystring = require('querystring');


//带着token请求接口
function post(url, postparam) {
    var config = {
        method: 'post',
        url: url,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + tokeninfo.access_token
        },
        data: JSON.stringify(postparam)
    };

    return new Promise((resolve, reject) => {
        axios(config)
            .then(response => {
                let retinfo = dealEpointJson(response.data);
                if (retinfo.status) {
                    return resolve(retinfo);
                } else {
                    throw retinfo.text;
                }
            })
            .catch(error => {
                // console.error(error);
                return reject(error);
            });
    })
}


function postfile(url, postparam, file) {
    let param = new FormData(); // 创建form对象
    param.append("file", file); // 通过append向form对象添加数据

    var config = {
        method: 'post',
        url: url,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': 'Bearer ' + tokeninfo.access_token
        },
        data: param,
        params: postparam
    };

    return new Promise((resolve, reject) => {
        axios(config)
            .then(response => {
                let retinfo = dealEpointJson(response.data);
                if (retinfo.status) {
                    return resolve(retinfo);
                } else {
                    throw retinfo.text;
                }
            })
            .catch(error => {
                // console.error(error);
                return reject(error);
            });
    })
}

function dealEpointJson(responsedata) {
    // console.log(JSON.stringify(str));
    let resdata = responsedata;
    var retinfo = {
        custom: JSON.parse(resdata.custom),
        text: resdata.status.text,
        status: resdata.status.code == "1" ? true : false
    };

    return retinfo;
}


module.exports.post = post;
module.exports.postfile = postfile;
